<template>
  <inline-Modal
    :visible="visible"
    title="查看"
    :showOk="false"
    @cancel="handelCancel()"
  >
    <div class="problem-rect-container">
      <div class="operate">
        <a-button
          v-if="showButton && soucre.approveStatus == 1"
          @click="gotoAdd()"
          class="cu-btn-primary margin-bottom-xs"
          icon="plus"
        >
          新增
        </a-button>
      </div>
      <div class="table-list-container">
        <vxe-table
          ref="xTable"
          height="99%"
          align="center"
          show-overflow
          show-header-overflow
          border="inner"
          :data="tableData"
          :column-config="{ resizable: true }"
          size="small"
          :loading="loading"
        >
          <vxe-column type="seq" width="80" title="序号"></vxe-column>
          <vxe-column field="type" title="类型"> </vxe-column>
          <vxe-column field="recordPeopleName" title="记录人"> </vxe-column>
          <vxe-column field="recordTime" title="记录时间"> </vxe-column>
          <vxe-column field="rectifyEndTime" title="整改截止时间"> </vxe-column>
          <vxe-column field="issueDescribe" title="问题描述"> </vxe-column>
          <vxe-column title="状态">
            <template #default="{ row }">
              <div :class="[checkStatusClass(row)]">
                {{ checkStatusName(row) }}
              </div>
            </template>
          </vxe-column>
          <vxe-column
            field="operate"
            width="280"
            title="操作"
            fixed="right"
            align="left"
          >
            <template #default="{ row }">
              <div class="text-button-group">
                <a-button
                  type="link"
                  @click="handelSubmit(row)"
                  v-if="showButton && row.statusFlag"
                  :loading="submitLoading"
                >
                  提交
                </a-button>
                <a-button
                  type="link"
                  @click="editor(row)"
                  v-if="showButton && row.approveStatus == 0"
                >
                  编辑
                </a-button>
                <a-button
                  type="link"
                  @click="gotoFlow(row)"
                  v-if="row.approveStatus != 0"
                >
                  流程图
                </a-button>
                <a-button
                  type="link"
                  @click="gotoApprovalRecord(row)"
                  v-if="row.approveStatus != 0"
                >
                  审批记录
                </a-button>
                <a-button
                  type="link"
                  class="danger"
                  @click="handleDelClick(row)"
                  v-if="showButton && row.approveStatus == 0"
                >
                  删除
                </a-button>
              </div>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div class="pager-container">
        <vxe-pager
          size="small"
          background
          :current-page.sync="pager.page"
          :page-size.sync="pager.pageSize"
          :total="pager.total"
          :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes']"
          :page-sizes="[20, 50, 100, 500]"
          @page-change="paginationChange"
        >
          <template #left>
            <div class="vxe-pager-left-tip-container">
              共<span>{{ pager.total }}</span
              >条
            </div>
          </template>
        </vxe-pager>
      </div>
    </div>
    <!-- 编辑弹窗-->
    <edit-form
      ref="createModal"
      :visible="editVisible"
      :loading="confirmLoading"
      :url="url"
      requestMethod="post"
      :tableDataType="tableDataType"
      @cancel="editCancel()"
      @ok="editOk()"
    />
    <flowChat ref="flowChatForm"></flowChat>
    <comment-modal ref="commentModal"></comment-modal>
  </inline-Modal>
</template>

<script>
import editForm from "@/pages/form/formPreview/edit.vue";
import commentModal from "@/pages/workflow/oaLeave/comment.vue";
import flowChat from "@/pages/workflow/apiFlowableTask/myMission/flowChat.vue";
import {
  pageCheckIssue,
  deleteCheckIssue,
  submitCheckIssue,
  getTaskPermission,
} from "@/api/safetyManage";
export default {
  components: {
    editForm,
    commentModal,
    flowChat,
  },
  provide() {
    // 使用函数的形式，可以访问到 `this`
    return {
      extraParamsValue: () => this.extraParams,
    };
  },
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    soucre: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },

  watch: {
    visible: {
      handler(val) {
        this.$emit("update:visible", val);
        if (val) {
          this.getPermission();
          this.getTableData();
        }
      },
      immediate: true,
    },
  },
  data() {
    return {
      showButton: false,
      extraParams: {},
      //列表
      loading: false,
      tableData: [],
      pager: {
        page: 1,
        pageSize: 20,
        total: 0,
      },
      editVisible: false,
      confirmLoading: false,
      url: {
        save: "/form/formDatabase/formSave",
        update: "/form/formDatabase/formUpdate",
      },
      tableDataType: "",
      tableUuid: "90D36D8B3E6A4530AB5F4AC1D107507B",
      modalFooter: {},
      submitLoading: false,
    };
  },
  methods: {
    //查询操作权限
    getPermission() {
      return new Promise((reslove, reject) => {
        let { tenantCode, pageType } = this.soucre;
        getTaskPermission({ tenantCode, type: pageType })
          .then((res) => {
            this.showButton = res?.data ?? false;
            reslove();
          })
          .catch((_) => {
            this.showButton = false;
            reject();
          });
      });
    },

    checkStatusName(row) {
      let { approveStatus } = row;
      switch (approveStatus) {
        case "0":
          return "未提交";
        case "2":
          return "已完成";
        default:
          return "审批中";
      }
    },
    checkStatusClass(row) {
      let { approveStatus } = row;
      switch (approveStatus) {
        case "0":
          return "no";
        case "2":
          return "status";
        default:
          return "default";
      }
    },
    //提交
    handelSubmit(row) {
      let dataLength = this.tableData.length;
      let that = this;
      that.$confirm({
        title: "提示",
        content: "确定提交该数据吗？",
        okText: "确定",
        cancelText: "取消",
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          that.submitLoading = true;
          submitCheckIssue({ uuid: row.uuid })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                that.$message.success("提交成功", 1.5);
                if (dataLength == 1 && that.pager.page > 1) {
                  that.pager.page -= 1;
                }
                that.getTableData();
              } else {
                that.$message.error(res.message);
              }
            })
            .catch((_) => {})
            .finally((_) => {
              that.submitLoading = false;
            });
        },
      });
    },

    //流程图
    gotoFlow(record) {
      this.$post("/workflow/oaLeave/clickFlowChart", {
        uuid: record.uuid,
      }).then((res) => {
        if (res.statusCode != 300) {
          const jsonData = res;
          this.$refs.flowChatForm.loadData(
            jsonData,
            jsonData.lists.actDeModelId,
            jsonData.lists.actDeModelKey,
            jsonData.lists.actDeModelName,
            jsonData.lists.flowDesign,
            record
          );
        } else {
          this.$message.error(res.message);
        }
      });
    },
    //审批记录
    gotoApprovalRecord(record) {
      this.$refs.commentModal.getCommentList(record.uuid);
    },
    async gotoAdd() {
      this.modalFooter = {};
      let { tenantCode, orgCode, uuid } = this.soucre;
      this.extraParams = {
        pro_code: tenantCode,
        org_code: `${orgCode}@${uuid}`,
      };
      this.editVisible = true;
      this.$refs.createModal.title = "新增";
      let formJsonData = await this.loadDataJson();
      let { addApiUrl } = JSON.parse(formJsonData)?.config ?? {};
      this.url.save = addApiUrl ?? "/form/formDatabase/formSave";
      this.$refs.createModal.loadData(this.tableUuid, "add", formJsonData);
    },
    //编辑
    async editor(record = {}) {
      let { tenantCode, orgCode, uuid } = this.soucre;
      this.extraParams = {
        pro_code: tenantCode,
        org_code: `${orgCode}@${uuid}`,
      };
      this.editVisible = true;
      let formJsonData = await this.loadDataJson();
      let { editApiUrl } = JSON.parse(formJsonData)?.config ?? {};
      this.url.update = editApiUrl ?? "/form/formDatabase/formSave";
      this.$refs.createModal.title = "编辑";
      this.$refs.createModal.loading = true;
      this.$post("/form/formDatabase/formGetDetail", {
        uuid: record.uuid,
        formUuid: this.tableUuid,
      }).then((res) => {
        this.$refs.createModal.loadData(
          this.tableUuid,
          "edit",
          formJsonData,
          res
        );
      });
    },

    loadDataJson() {
      return new Promise((reslove) => {
        this.$post("/form/formBasicConfigure/getDetailByUuid", {
          uuid: this.tableUuid,
        })
          .then((res) => {
            this.tableDataType = res.formDatabase?.type || "";
            reslove(res.formDesign.designJson);
          })
          .catch((_) => {
            reslove({});
          });
      });
    },

    //删除
    handleDelClick(row) {
      let dataLength = this.tableData.length;
      let that = this;
      that.$confirm({
        title: "提示",
        content: "确定删除该数据吗？删除之后不可恢复！",
        okText: "确定",
        cancelText: "取消",
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          deleteCheckIssue({ uuid: row.uuid })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                that.$message.success("删除成功", 1.5);
                if (dataLength == 1 && that.pager.page > 1) {
                  that.pager.page -= 1;
                }
                that.getTableData();
              } else {
                that.$message.error(res.message);
              }
            })
            .catch((_) => {});
        },
      });
    },

    //关闭弹窗
    editCancel() {
      this.editVisible = false;
    },

    editOk() {
      this.editVisible = false;
      this.getTableData();
    },
    //查询列表数据
    getTableData() {
      this.loading = true;
      let { page, pageSize } = this.pager;
      let { uuid } = this.soucre;
      pageCheckIssue({
        page,
        pageSize,
        zhgdCheckUnitId: uuid,
      })
        .then((res) => {
          this.tableData = res?.rows || [];
          this.pager.total = res?.totalCount || 0;
        })
        .catch((_) => {
          this.tableData = [];
          this.pager.total = 0;
        })
        .finally((_) => {
          this.loading = false;
        });
    },

    //监听分页切换
    paginationChange({ currentPage, pageSize }) {
      this.pager.page = currentPage;
      this.pager.pageSize = pageSize;
      this.getTableData();
    },
    handelCancel() {
      this.$emit("cancel");
    },
  },
};
</script>

<style lang="less" scoped>
.problem-rect-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  .table-list-container {
    flex: 1;
    .status {
      color: #4bc964;
    }
    .no {
      color: #1677ff;
    }
    .default {
      color: #ff993f;
    }
  }
}
</style>
